package com.declum.archon.chunkserver.handler.request;

import java.nio.charset.Charset;
import java.nio.charset.CharsetDecoder;

import org.apache.mina.common.ByteBuffer;
import org.apache.mina.common.IoSession;

import com.declum.archon.chunkserver.server.IChunkServer;

/**
 * Used to create Request handler based on the Client's Command
 * 
 * @author Clement
 * 
 */
public class RequestHandlerFactory implements RequestHandlerType {
	CharsetDecoder					decoder;
	IChunkServer					server;

	static RequestHandlerFactory	singleton;

	public RequestHandlerFactory() {
		this.decoder = Charset.defaultCharset().newDecoder();
	}

	public static RequestHandlerFactory getInstance() {
		if (RequestHandlerFactory.singleton == null) {
			RequestHandlerFactory.singleton = new RequestHandlerFactory();
		}
		return RequestHandlerFactory.singleton;
	}

	public IRequest getRequestInstance(IoSession session, ByteBuffer buffer)
			throws Exception {
		IRequest request = null;

		String type = buffer.getString(this.decoder);
		if (type.equals(RequestHandlerType.PING)) {
			request = new PingRequestHandler();
		} else if (type.equals(RequestHandlerType.CREATE_CHUNK)) {
			request = new CreateChunkRequestHandler();
			session.setAttribute("info", new CreateChunkInfo());
		} else {
			request = new FakeRequestHandler();
		}
		request.setServerInstance(this.server);
		buffer.clear();
		return request;
	}

	/**
	 * Sets the Serve instance for the factory
	 * 
	 * @param server
	 */
	public static void initialize(IChunkServer server) {
		RequestHandlerFactory.getInstance().server = server;
	}
}
